package com.acme.serialization.impl;

import com.acme.serialization.ObjectSerializer;
import com.acme.serialization.SensorData;
import com.acme.serialization.SerializationException;
import com.acme.serialization.protobuf.SensorDataProto;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Gregory Sobko
 */
public class ProtobufSensorDataSerializer implements ObjectSerializer<SensorData[]> {
    @Override
    public String getProtocolName() {
        return "protobuf";  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public SensorData[] deserialize(InputStream inputStream) throws SerializationException {
        try {
            SensorDataProto.SensorDataBatch sensorDataBatch =
                    SensorDataProto.SensorDataBatch.parseDelimitedFrom(inputStream);
            int length = sensorDataBatch.getDataCount();
            List<SensorData> sensorDataList = new ArrayList<>(length);
            for (SensorDataProto.SensorDataBatch.SensorData sensorDataProto : sensorDataBatch.getDataList()) {
                sensorDataList.add(new SensorData(
                        sensorDataProto.getLongitude(),
                        sensorDataProto.getLatitude(),
                        sensorDataProto.getElevation(),
                        sensorDataProto.getTemperature()));
            }
            return sensorDataList.toArray(new SensorData[sensorDataList.size()]);
        } catch (IOException e) {
            throw new SerializationException(e);
        }
    }

    @Override
    public void serialize(SensorData[] object, OutputStream outputStream) throws SerializationException {
        SensorDataProto.SensorDataBatch.Builder sensorDataBatchBuilder = SensorDataProto.SensorDataBatch.newBuilder();
        for (SensorData sensorData : object) {
            sensorDataBatchBuilder.addData(
                    SensorDataProto.SensorDataBatch.SensorData.newBuilder()
                            .setElevation(sensorData.getElevation())
                            .setLatitude(sensorData.getLatitude())
                            .setLongitude(sensorData.getLongitude())
                            .setTemperature(sensorData.getTemperature())
                            .build()
            );
        }

        try {
            sensorDataBatchBuilder.build().writeDelimitedTo(outputStream);
        } catch (IOException e) {
            throw new SerializationException(e);
        }
    }
}
